/*
 * Copyright (c) 2013 Eugene Kuzmenko
 *
 * Permission  is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in  the Software without restriction, including without limitation the rights
 * to  use,  copy,  modify,  merge, publish, distribute, sublicense, and/or sell
 * copies  of  the  Software,  and  to  permit  persons  to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The  above  copyright  notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE  SOFTWARE  IS  PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED,  INCLUDING  BUT  NOT  LIMITED  TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS  FOR  A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS  OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR  ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * For more information, see <http://www.aljey.com>.
 */

//=../Button/Text

/**
 * A combo box component.
 *
 * @author Eugene Kuzmenko <mail@aljey.com>
 * @class {Combo}
 * @extends {Container}
 */
Class.define('Combo', {

  extend: 'Container',

  /**
   * A label to show with this field.
   *
   * @property {string}
   */
  label: '',

  /**
   * True to make the field required.
   *
   * @property {bool}
   */
  required: true,

  /**
   * True to allow the selection of multiple items at once.
   *
   * @property {bool}
   */
  multiple: false,

  /**
   * The default width.
   *
   * @property {number}
   */
  width: 300,

  /** @constructs */
  init: function () {
    _super();
    this.options = this.options || [];
    _.isArray(this.options) || (this.options = [this.options]);
    this.options = _.map(this.options, function (option) {
      return _.isPlainObject(option) ? option : {id: option, value: option}
    });
  },

  /**
   * Sets the value.
   *
   * @param {number|string} val
   * @param {bool} [silent] If true the change event will not fire.
   * @returns {Combo}
   */
  setValue: function (val, silent) {
    this._field && this._field.val(_.filter(_.isArray(val) ? val : [val],
      function (v) {
        return _.where(this.options, {id: v});
      }, this));
    silent || this.fire('change');
    return this;
  },

  /**
   * Retrieves the field value.
   *
   * @returns {string}
   */
  getValue: function () { return this._field && this._field.val() },

  /**
   * Makes the field required.
   *
   * @param {bool} required
   * @returns {Combo}
   */
  setRequired: function (required) {
    this.required = !!required;
    this.isValid();
    return this;
  },

  /**
   * Sets the label.
   *
   * @param {string} val
   * @returns {Combo}
   */
  setLabel: _static.Container.setter(function (val) {
    val && !this._label && (this._label = Class.create('Text', {
      renderTo: this.el,
      prependMode: true
    }).show());
    this._label && this._label.setValue(val ? (val + ': ') : '');
  }, 'label', 'string'),

  /**
   * Sets the field width.
   *
   * @param {*} val
   * @returns {Combo}
   */
  setFieldWidth: _static.Container.setter(function (val) {
    this._field.width(val);
  }, 'fieldWidth', 'string', '100%'),

  /**
   * Sets the field height.
   *
   * @param {*} val
   * @returns {Combo}
   */
  setFieldHeight: _static.Container.setter(function (val) {
    this._field.height(val);
  }, 'fieldHeight'),

  /**
   * [Dis]allows the selection of multiple items at once.
   *
   * @param {bool} val
   * @returns {Combo}
   */
  setMultiple: _static.Container.setter(function (val) {
    val ? this._field.attr('multiple', 'multiple') : this._field.removeAttr();
  }, 'multiple', 'bool'),

  /**
   * Checks the validity of the field.
   *
   * @returns {bool}
   */
  isValid: function () {
    var val = this.getValue();
    if (val) {
      if (this.el) {
        this.el.removeClass('has-error');
        this._field.tooltip('hide');
      }
      return true;
    }
    if (this.required) {
      if (this.el) {
        this.el.addClass('has-error');
        this._field.tooltip('show');
      }
      return false;
    }
    if (this.el) {
      this.el.removeClass('has-error');
      this._field.tooltip('hide');
    }
    return true;
  },

  tpl: [
    '<label class="al-field-sm">',
      '<select class="form-control input-sm" data-toggle="tooltip"',
          ' data-trigger="manual" data-title="', Al.trans('error.required'),
          '"<%if(multiple){%> multiple="multiple"<%}%>>',
        '<%_.each(options,function(option){%>',
          '<option value="<%=option.id%>"><%=option.value%></option>',
        '<%});%>',
      '</select>',
    '</label>'
  ],

  listeners: {
    beforeRender: function () {
      var me = this;
      (me._field = me.el.find('select')).change(function () {
        me.fire('change');
      });
      ('value' in this) && this.setValue(this.value);
      if ('label' in this) {
        var label = this.label;
        this.label = null;
        this.setLabel(label);
      }
      if ('fieldWidth' in this) {
        var fieldWidth = this.fieldWidth;
        this.fieldWidth = null;
        this.setFieldWidth(fieldWidth);
      }
      if ('fieldHeight' in this) {
        var fieldHeight = this.fieldHeight;
        this.fieldHeight = null;
        this.setFieldHeight(fieldHeight);
      }
    },
    change: function () { this.isValid() }
  }

});